package offer;

import java.util.ArrayList;
import java.util.Stack;

/**
 * @Author SSK
 * @Date Created in 21:15 2019/8/7
 * @Description 按之字形顺序打印二叉树
 * @Version 1.0
 */
public class T60 {
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }

    }
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
        if (pRoot==null) {
            return lists;
        }
        Stack<TreeNode> stack1 = new Stack<TreeNode>();
        stack1.add(pRoot);
        Stack<TreeNode> stack2 = new Stack<TreeNode>();
        while (!stack1.isEmpty()||!stack2.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            if (stack1.isEmpty()) {
                    while (!stack2.isEmpty()) {
                        TreeNode node = stack2.pop();
                        list.add(node.val);
                        if (node.right!=null) {
                            stack1.push(node.right);
                        }
                        if (node.left!=null) {
                           stack1.push(node.left);
                        }
                    }

            }else {

                while (!stack1.isEmpty()) {
                    TreeNode node = stack1.pop();
                    list.add(node.val);
                    if (node.left!=null) {
                        stack2.push(node.left);
                    }
                    if (node.right!=null) {
                        stack2.push(node.right);
                    }
                }
            }
            if (list.size()!=0) {
                lists.add(list);
            }
        }
        return lists;
    }
}
